package com.jdyxk.commons.mybatis;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

/**
 * @author 李昊哲
 * @Description
 * @createTime 2021/8/4 上午10:42
 */
public class MybatisUtil {
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
    private static SqlSessionFactory sqlSessionFactory;

    static {
        Reader reader = null;
        try {
            // 核心配置文件classpath路径
            String resource = "mybatis/mybatis-config.xml";
            // 加载配置文件
            reader = Resources.getResourceAsReader(resource);
            // 构建会话工厂
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取SqlSession
     *
     * @return SqlSession
     */
    public static SqlSession openSqlSession() {
        if (threadLocal.get() != null) {
            return threadLocal.get();
        }
        SqlSession sqlSession = sqlSessionFactory.openSession();
        threadLocal.set(sqlSession);
        return sqlSession;
    }

    /**
     * 归还连接给数据源
     */
    public static void close(){
        if (threadLocal.get() != null) {
            SqlSession sqlSession = threadLocal.get();
            threadLocal.remove();
            sqlSession.close();
        }
    }
    /**
     * 归还连接给数据源并手动提交事务
     */
    public static void commitAndClose(){
        if (threadLocal.get() != null) {
            SqlSession sqlSession = threadLocal.get();
            threadLocal.remove();
            sqlSession.commit();
            sqlSession.close();
        }
    }
    /**
     * 归还连接给数据源 事务回滚
     */
    public static void rollbackAndClose(){
        if (threadLocal.get() != null) {
            SqlSession sqlSession = threadLocal.get();
            threadLocal.remove();
            sqlSession.rollback();
            sqlSession.close();
        }
    }
}
